package com.zhihuiyanche.controller.checkcar;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.collections.map.ListOrderedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.zhihuiyanche.common.util.CheckoutUtil;
import com.zhihuiyanche.common.util.CommonUtil;
import com.zhihuiyanche.domain.CheckCar;
import com.zhihuiyanche.domain.ListResult;
import com.zhihuiyanche.domain.Orders;
import com.zhihuiyanche.domain.Shops;
import com.zhihuiyanche.domain.WeixinUserInfo;
import com.zhihuiyanche.service.checkcar.CheckCarService;
import com.zhihuiyanche.service.orders.OrdersService;
import com.zhihuiyanche.service.shops.ShopsService;

@RestController
public class CheckCarController
{
	@Autowired
	private CheckCarService	checkCarService;

	@Autowired
	private ShopsService	shopsService;

	@Autowired
	private OrdersService	ordersService;

	/**
	 * 查询车辆信息页面
	 * 
	 * @param checkCar
	 * @param req
	 * @param resp
	 * @param context
	 * @return
	 */
	@RequestMapping(value = "checkCarQuery", method =
	{ RequestMethod.POST, RequestMethod.GET })
	public ModelAndView checkCarQuery(CheckCar checkCar, HttpServletRequest req, HttpServletResponse resp, HttpSession session, ModelMap context){
		boolean isGet = req.getMethod().toLowerCase().equals("get");
        PrintWriter print = null;
        if (isGet) {
            String signature = req.getParameter("signature");// 微信加密签名
            String timestamp = req.getParameter("timestamp");// 时间戳
            String nonce = req.getParameter("nonce");// 随机数
            String echostr = req.getParameter("echostr");// 随机字符串
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
            if (signature != null && CheckoutUtil.checkSignature(signature, timestamp, nonce)) {
                try {
                    print = resp.getWriter();
                    print.write(echostr);
                    print.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                	if(print!=null){
                		print.close();
                	}
                }
            }
        }
	        
		ModelAndView mv = new ModelAndView();
		mv.setViewName("wx/index_1");
		return mv;
	}

	/**
	 * 查询车辆信息页面
	 * 
	 * @param checkCar
	 * @param req
	 * @param resp
	 * @param context
	 * @return
	 */
	@RequestMapping(value = "myCheckCarMgmt", produces = "application/json; charset=utf-8", method ={RequestMethod.POST})
	public @ResponseBody String myCheckCarMgmt(CheckCar checkCar, HttpServletRequest req, HttpServletResponse resp, HttpSession session, ModelMap context){
	
		// 获取接口访问凭证
	    String accessToken = CommonUtil.getToken("wxaee49617bd4f23b1", "6f9b70c52cbb6336b4c371f0c5a6e1c9").getAccessToken();
	    /**
	     * 获取用户信息
	     */
	    WeixinUserInfo user = getUserInfo(accessToken, "ooK-yuJvd9gEegH6nRIen-gnLrVw");
	    System.out.println("===================================");
	    System.out.println("===================================");
	    System.out.println("===================================");
	    System.out.println("===================================");
	    System.out.println("===================================");
	    System.out.println("OpenID：" + user.getOpenId());
	    System.out.println("关注状态：" + user.getSubscribe());
	    System.out.println("关注时间：" + user.getSubscribeTime());
	    System.out.println("昵称：" + user.getNickname());
	    System.out.println("性别：" + user.getSex());
	    System.out.println("国家：" + user.getCountry());
	    System.out.println("省份：" + user.getProvince());
	    System.out.println("城市：" + user.getCity());
	    System.out.println("语言：" + user.getLanguage());
	    System.out.println("头像：" + user.getHeadImgUrl());
	    System.out.println("===================================");
	    System.out.println("===================================");
	    System.out.println("===================================");
	    System.out.println("===================================");
	    System.out.println("===================================");
		
		ListResult result = new ListResult();
		result.setSuccess(true);
		try {
			if (session.getAttribute("customerId") == null) {
				// 从微信端获取客户信息 并入库
				checkCar.setName("王小二");// 从微信端获取 -- 先写死
				checkCar.setMobile("18299988868");// 从微信端获取 -- 先写死

				String customerId = checkCarService.insertCustomer(checkCar);
				session.setAttribute("customerId", customerId);
				checkCar.setCustomerId(customerId);
			} else {
				checkCar.setCustomerId((String) session.getAttribute("customerId"));
			}
			int size = 0;
			List<CheckCar> list = checkCarService.queryMyCar(checkCar);
			if(list!=null){
				size = list.size();
			}
			result.setRows(list);
			result.setTotal(size);
		} catch (Exception e) {
			result.setSuccess(false);
			result.setMessage(e.getMessage());
		}
		
		return JSONObject.fromObject(result).toString();
	}
	
	/**
	 * 查询车辆信息页面
	 * 
	 * @param checkCar
	 * @param req
	 * @param resp
	 * @param context
	 * @return
	 */
	@RequestMapping(value = "myOrderMgmt", produces = "application/json; charset=utf-8", method ={ RequestMethod.POST})
	public @ResponseBody String myOrderMgmt(CheckCar checkCar, HttpServletRequest req, HttpServletResponse resp, HttpSession session, ModelMap context){
		ListResult result = new ListResult();
		result.setSuccess(true);
		try {
			if (session.getAttribute("customerId") == null) {
				// 从微信端获取客户信息 并入库
				checkCar.setName("王小二");// 从微信端获取 -- 先写死
				checkCar.setMobile("18299988868");// 从微信端获取 -- 先写死
				
				String customerId = checkCarService.insertCustomer(checkCar);
				session.setAttribute("customerId", customerId);
				checkCar.setCustomerId(customerId);
			} else {
				checkCar.setCustomerId((String) session.getAttribute("customerId"));
			}
			int size = 0;
			List<CheckCar> list = checkCarService.queryMyCheckCar(checkCar);
			if(list!=null){
				size = list.size();
			}
			result.setRows(list);
			result.setTotal(size);
		} catch (Exception e) {
			result.setSuccess(false);
			result.setMessage(e.getMessage());
		}
		
		return JSONObject.fromObject(result).toString();
	}
	
	/**
	 * 添加车辆信息初始页
	 * 
	 * @param checkCar
	 * @param req
	 * @param resp
	 * @param context
	 * @return
	 */
	@RequestMapping(value = "checkCarAddPre", produces = "application/json; charset=utf-8", method ={ RequestMethod.POST})
	public @ResponseBody String  checkCarAddPre(CheckCar checkCar, HttpServletRequest req, HttpServletResponse resp, HttpSession session, ModelMap context){
		ListResult result = new ListResult();
		result.setSuccess(true);
		return JSONObject.fromObject(result).toString();
	}

	/**
	 * 添加车辆信息
	 * 
	 * @param checkCar
	 * @param req
	 * @param resp
	 * @param context
	 * @return
	 */
	@RequestMapping(value = "checkCarAdd", produces = "application/json; charset=utf-8", method ={RequestMethod.POST})
	public @ResponseBody String checkCarAdd(CheckCar checkCar, HttpServletRequest req, HttpServletResponse resp, HttpSession session, ModelMap context){
		ListResult result = new ListResult();
		result.setSuccess(true);
		
		Map<String, Object> map = parseJSON2Map(checkCar.getSaveData());
		checkCar = mapTocheckCar(map);
		checkCar.setCustomerId((String) session.getAttribute("customerId"));
		checkCarService.insertCarService(checkCar);
		
		try {
			if (session.getAttribute("customerId") == null) {
				// 从微信端获取客户信息 并入库
				checkCar.setName("王小二");// 从微信端获取 -- 先写死
				checkCar.setMobile("18299988868");// 从微信端获取 -- 先写死

				String customerId = checkCarService.insertCustomer(checkCar);
				session.setAttribute("customerId", customerId);
				checkCar.setCustomerId(customerId);
			} else {
				checkCar.setCustomerId((String) session.getAttribute("customerId"));
			}
			int size = 0;
			List<CheckCar> list = checkCarService.queryMyCar(checkCar);
			if(list!=null){
				size = list.size();
			}
			result.setRows(list);
			result.setTotal(size);
		} catch (Exception e) {
			result.setSuccess(false);
			result.setMessage(e.getMessage());
		}
		
		return JSONObject.fromObject(result).toString();
	}

	/**
	 * 验车初始页
	 * 
	 * @param checkCar
	 * @param req
	 * @param resp
	 * @param context
	 * @return
	 */
	@RequestMapping(value = "checkCarPre", produces = "application/json; charset=utf-8", method ={RequestMethod.POST})
	public @ResponseBody String checkCarPre(CheckCar checkCar, HttpServletRequest req, HttpServletResponse resp, HttpSession session, ModelMap context){
		try {
			Shops shops = new Shops();
			// shops.setCity(city);//设置城市条件根据 城市条件进行过滤
			List<Shops> list = shopsService.getShopsAll(shops);
			checkCar.setShopsList(list);
			
			Map<String, Object> map = parseJSON2Map(checkCar.getSaveData());
			checkCar.setVehicleId(map.get("vehicleId").toString());
			checkCar.setPlateNo(map.get("plateNo").toString());
			checkCar.setOwner(map.get("owner").toString());
			checkCar.setRegisterDate(map.get("registerDate").toString());
			checkCar.setVehicleType(map.get("vehicleType").toString());
			checkCar.setVin(map.get("vin").toString());
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return JSONObject.fromObject(checkCar).toString();
	}

	/**
	 * 验车日期
	 * 
	 * @param checkCar
	 * @param req
	 * @param resp
	 * @param context
	 * @return
	 */
	@RequestMapping(value = "checkCarConfirm", produces = "application/json; charset=utf-8", method ={RequestMethod.POST})
	public @ResponseBody String checkCarConfirm(CheckCar checkCar, HttpServletRequest req, HttpServletResponse resp, HttpSession session, ModelMap context){
		Map<String, Object> map = parseJSON2Map(checkCar.getSaveData());
		checkCar.setVehicleId(map.get("vehicleId").toString());
		checkCar.setPlateNo(map.get("plateNo").toString());
		checkCar.setOwner(map.get("owner").toString());
		checkCar.setRegisterDate(map.get("registerDate").toString());
		checkCar.setVehicleType(map.get("vehicleType").toString());
		checkCar.setVin(map.get("vin").toString());
		checkCar.setShopId(map.get("shopId").toString());
		checkCar.setDataList(returnString());
		return JSONObject.fromObject(checkCar).toString();
	}
	/**
	 * 验车日期
	 * 
	 * @param checkCar
	 * @param req
	 * @param resp
	 * @param context
	 * @return
	 */
	@RequestMapping(value = "checkDatatimeInfo", produces = "application/json; charset=utf-8", method ={RequestMethod.POST})
	public @ResponseBody String checkDatatimeInfo(CheckCar checkCar, HttpServletRequest req, HttpServletResponse resp, HttpSession session, ModelMap context){
		//返回一个list 包含四个字段  时间  数量  总数   是否已预约满
		List<Map<String,Object>> returnList = new ArrayList<Map<String,Object>>();
		Map<String, Object> map = parseJSON2Map(checkCar.getSaveData());
		checkCar.setVehicleId(map.get("vehicleId").toString());
		checkCar.setPlateNo(map.get("plateNo").toString());
		checkCar.setOwner(map.get("owner").toString());
		checkCar.setRegisterDate(map.get("registerDate").toString());
		checkCar.setVehicleType(map.get("vehicleType").toString());
		checkCar.setVin(map.get("vin").toString());
		checkCar.setOrderDate(map.get("orderDate").toString());
		checkCar.setShopId(map.get("shopId").toString());
		
		Shops queryShops = new Shops();
		queryShops.setId(checkCar.getShopId());
		Shops shops = shopsService.getShopsById(queryShops);
		if (shops != null){
			int maxOrderPerDay = 35; //默认初始最大订单量 35
			if (shops.getMaxOrderPerDay() != null){
				maxOrderPerDay = shops.getMaxOrderPerDay();
			}
			
			int firstStage = (maxOrderPerDay - maxOrderPerDay%6)/6; //最大量单
			
			int secondStage = (maxOrderPerDay - firstStage*4)/2;
			
			int thirdStage = maxOrderPerDay - firstStage * 4 - secondStage;
			
			int firstCount = 0;
			int secondCount = 0;
			int thirdCount = 0;
			int fouthCount = 0;
			int fifthCount= 0;
			int sixthCount = 0;
			
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-");
			
			Orders orders = new Orders();
			orders.setShopId(checkCar.getShopId());
			orders.setOrderDate(sf.format(new Date())+checkCar.getOrderDate());
			
			//得到订单信息
			List<Orders> orderList = ordersService.queryOrdersByCondition(orders);
			
			if(orderList!=null){
				for(Orders order : orderList){
					if("8:30-9:30".equals(order.getOrderTime())){
						firstCount ++;
					} else if("9:30-10:30".equals(order.getOrderTime())){
						secondCount ++;
					} else if("10:30-12:00".equals(order.getOrderTime())){
						thirdCount ++;
					} else if("14:00-15:00".equals(order.getOrderTime())){
						fouthCount ++;
					} else if("15:00-16:00".equals(order.getOrderTime())){
						fifthCount ++;
					} else {
						sixthCount ++;
					}
				}
			}
			
			//时间段
			Map<String,Object> map1 = new HashMap<String, Object>();
			Map<String,Object> map2 = new HashMap<String, Object>();
			Map<String,Object> map3 = new HashMap<String, Object>();
			Map<String,Object> map4 = new HashMap<String, Object>();
			Map<String,Object> map5 = new HashMap<String, Object>();
			Map<String,Object> map6 = new HashMap<String, Object>();
			map1.put("orderTime", "8:30-9:30");
			map1.put("totalCount", firstStage);
			if (firstCount < firstStage){
				map1.put("leftCount", firstStage - firstCount);
				map1.put("flag", "b"); //a:预约已满     b:未满
			} else {
				map1.put("leftCount", 0);
				map1.put("flag", "a"); //a:预约已满     b:未满
			}
			
			map2.put("orderTime", "9:30-10:30");
			map2.put("totalCount", firstStage);
			if (secondCount < firstStage){
				map2.put("leftCount", firstStage - secondCount);
				map2.put("flag", "b"); //a:预约已满     b:未满
			} else {
				map2.put("leftCount", 0);
				map2.put("flag", "a"); //a:预约已满     b:未满
			}
			
			map3.put("orderTime", "10:30-12:00");
			map3.put("totalCount", secondStage);
			if (thirdCount < secondStage){
				map3.put("leftCount", secondStage - thirdCount);
				map3.put("flag", "b"); //a:预约已满     b:未满
			} else {
				map3.put("leftCount", 0);
				map3.put("flag", "a"); //a:预约已满     b:未满
			}
			
			map4.put("orderTime", "14:00-15:00");
			map4.put("totalCount", firstStage);
			if (fouthCount < firstStage){
				map4.put("leftCount", firstStage - fouthCount);
				map4.put("flag", "b"); //a:预约已满     b:未满
			} else {
				map4.put("leftCount", 0);
				map4.put("flag", "a"); //a:预约已满     b:未满
			}
			
			map5.put("orderTime", "15:00-16:00");
			map5.put("totalCount", firstStage);
			if (fifthCount < firstStage){
				map5.put("leftCount", firstStage - fifthCount);
				map5.put("flag", "b"); //a:预约已满     b:未满
			} else {
				map5.put("leftCount", 0);
				map5.put("flag", "a"); //a:预约已满     b:未满
			}
			
			map6.put("orderTime", "16:00-17:30");
			map6.put("totalCount", thirdStage);
			if (sixthCount < thirdStage){
				map6.put("leftCount", thirdStage - sixthCount);
				map6.put("flag", "b"); //a:预约已满     b:未满
			} else {
				map6.put("leftCount", 0);
				map6.put("flag", "a"); //a:预约已满     b:未满
			}
			
			returnList.add(map1);
			returnList.add(map2);
			returnList.add(map3);
			returnList.add(map4);
			returnList.add(map5);
			returnList.add(map6);
		}
		Map<String,Object> returnMap = new HashMap<String, Object>();
		returnMap.put("data", returnList);
		returnMap.put("checkCar", checkCar);
		return JSONObject.fromObject(returnMap).toString();
	}

	/**
	 * @param checkCar
	 * @param req
	 * @param resp
	 * @param context
	 * @return
	 */
	@RequestMapping(value = "checkCar", produces = "application/json; charset=utf-8", method ={RequestMethod.POST})
	public @ResponseBody String checkCar(CheckCar checkCar, HttpServletRequest req, HttpServletResponse resp, HttpSession session, ModelMap context){
		Map<String, Object> map = parseJSON2Map(checkCar.getSaveData());
		checkCar.setShopId(map.get("shopId").toString());
		checkCar.setVehicleId(map.get("vehicleId").toString());
		
		checkCar.setPlateNo(map.get("plateNo").toString());
		checkCar.setOwner(map.get("owner").toString());
		checkCar.setRegisterDate(map.get("registerDate").toString());
		checkCar.setVehicleType(map.get("vehicleType").toString());
		checkCar.setVin(map.get("vin").toString());
		checkCar.setOrderTime(map.get("orderTime").toString());
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-");
		
		checkCar.setOrderDate(sf.format(new Date())+map.get("orderDate").toString());
		checkCar.setCustomerId((String) session.getAttribute("customerId"));

		checkCar.setId(checkCarService.checkCar(checkCar));
		
		return JSONObject.fromObject(checkCar).toString();
	}

	/**
	 * 查询验车数据信息 - 统计当前日期的30天内的
	 * 
	 * @param id
	 *            :shopId
	 * @return
	 */
	private List<String> returnString(){
		List<String> returnlist = new ArrayList<String>();

		SimpleDateFormat sf = new SimpleDateFormat("MM-dd");

		for (int i = 0; i < 7; i++) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(new Date()); // 设置时间为当前时间
			calendar.add(Calendar.DATE, i);
			String tempDate = sf.format(calendar.getTime());
			returnlist.add(tempDate);
		}

		return returnlist;
	}
	
	/**
	 * 查询验车数据信息 - 统计当前日期的7天内的
	 * 
	 * @param id
	 *            :shopId
	 * @return
	 */
	private List<String> returnHTML(String shopId){
		List<String> returnlist = new ArrayList<String>();
		
		Shops queryShops = new Shops();
		queryShops.setId(shopId);
		Shops shops = shopsService.getShopsById(queryShops);
		if (shops != null){
			int maxOrderPerDay = 10;
			if (shops.getMaxOrderPerDay() != null){
				maxOrderPerDay = shops.getMaxOrderPerDay();
			}
			
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
			
			for (int i = 1; i < 31; i++) {
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(new Date()); // 设置时间为当前时间
				calendar.add(Calendar.DATE, i);
				String tempDate = sf.format(calendar.getTime());
				
				JSONObject orders = new JSONObject();
				orders.put("shopId", shopId);
				orders.put("orderDate", tempDate);
				
				int tempOrderCount = ordersService.getOrdersByPageCount(orders);
				
				if (tempOrderCount < maxOrderPerDay) {
					returnlist.add("'c|" + tempDate + "'");
				}
			}
		}
		
		return returnlist;
	}

	public Map<String, Object> parseJSON2Map(String jsonStr){
		ListOrderedMap map = new ListOrderedMap();
		// 最外层解析
		JSONObject json = JSONObject.fromObject(jsonStr);
		for (Object k : json.keySet()) {
			Object v = json.get(k);
			// 如果内层还是数组的话，继续解析
			if (v instanceof JSONArray) {
				List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
				Iterator<JSONObject> it = ((JSONArray) v).iterator();
				while (it.hasNext()) {
					JSONObject json2 = it.next();
					list.add(parseJSON2Map(json2.toString()));
				}
				map.put(k.toString(), list);
			}
			else {
				map.put(k.toString(), v);
			}
		}
		return map;
	}

	public CheckCar mapTocheckCar(Map<String, Object> map){
		CheckCar checkCar = new CheckCar();
			checkCar.setVehicleType(map.get("vehicleType").toString());
			checkCar.setAddress(map.get("address").toString());
			checkCar.setPlateNo(map.get("plateNo").toString());
			checkCar.setOwner(map.get("owner").toString());
			checkCar.setEngineNo(map.get("engineNo").toString());
			checkCar.setRegisterDate(map.get("registerDate").toString());
		return checkCar;
	}
	
	/**
	   * 获取用户信息
	   * 
	   * @param accessToken 接口访问凭证
	   * @param openId 用户标识
	   * @return WeixinUserInfo
	   */
	  public static WeixinUserInfo getUserInfo(String accessToken, String openId) {
	    WeixinUserInfo weixinUserInfo = null;
	    // 拼接请求地址
	    String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID";
	    requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
	    // 获取用户信息
	    JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
	    if (null != jsonObject) {
	      try {
	        weixinUserInfo = new WeixinUserInfo();
	        // 用户的标识
	        weixinUserInfo.setOpenId(jsonObject.getString("openid"));
	        // 关注状态（1是关注，0是未关注），未关注时获取不到其余信息
	        weixinUserInfo.setSubscribe(jsonObject.getInt("subscribe"));
	        // 用户关注时间
	        weixinUserInfo.setSubscribeTime(jsonObject.getString("subscribe_time"));
	        // 昵称
	        weixinUserInfo.setNickname(jsonObject.getString("nickname"));
	        // 用户的性别（1是男性，2是女性，0是未知）
	        weixinUserInfo.setSex(jsonObject.getInt("sex"));
	        // 用户所在国家
	        weixinUserInfo.setCountry(jsonObject.getString("country"));
	        // 用户所在省份
	        weixinUserInfo.setProvince(jsonObject.getString("province"));
	        // 用户所在城市
	        weixinUserInfo.setCity(jsonObject.getString("city"));
	        // 用户的语言，简体中文为zh_CN
	        weixinUserInfo.setLanguage(jsonObject.getString("language"));
	        // 用户头像
	        weixinUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));
	      } catch (Exception e) {
	        if (0 == weixinUserInfo.getSubscribe()) {
	          System.out.println("用户{}已取消关注"+weixinUserInfo.getOpenId());
	        } else {
	          int errorCode = jsonObject.getInt("errcode");
	          String errorMsg = jsonObject.getString("errmsg");
	          System.out.println("获取用户信息失败 errcode:{} errmsg:{}"+errorCode+errorMsg);
	        }
	      }
	    }
	    return weixinUserInfo;
	  }
}